<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\model;
use think\Model;
use think\facade\Db;

class Module extends Model{
	protected $auto = ['initial_hits'];

    // urlroute
    protected function setUrlrouteAttr(){
    	// 转为小写字母
		return strtolower(input('urlroute'));
    }

	//初始点击数
    protected function setInitialHitsAttr(){
    	$min_hits = input('min_hits'); $max_hits = input('max_hits');
    	if(!empty($min_hits) and !empty($min_hits)){
    		$initial_hits = $min_hits.','.$max_hits;
		    return $initial_hits;
    	}else{
    		return true;
    	}
    }
	
	//目录
    protected function setTabledirAttr(){
    	// 转为小写字母
    	$general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));
        
		return $tabledir;
    }
	
	//是否显示
    protected function setIsdisplayAttr(){
		$isdisplay = '';
		$isdisplay_array = input('isdisplay/a');
        for($i=0;$i<count($isdisplay_array);$i++){
			$i<count($isdisplay_array)-1 ? $isdisplay.=$isdisplay_array[$i]."," : $isdisplay.=$isdisplay_array[$i];
	    }
		return $isdisplay;
    }
	
    // 新增/编辑
	static function edit($id){
		// 转为小写字母
    	$general = new \common\General();
    	$lang = $general->capital_to_underline(input('lang'));
        $tabledir = $general->capital_to_underline(input('tabledir'));
        $urlroute = $general->capital_to_underline(input('urlroute'));

		$dofile = new \common\Dofile();
		$auth = new \common\Auth(); $auth->check('','');
	    if($id>0){//编辑
			$moduleRs = Module::find($id);
			$oldModuleUrlroute = $moduleRs['urlroute'];
			//更新模块
			$result = $moduleRs->save(input('post.'));

			/*更新导航表：navigation 开始*/
			if($oldModuleUrlroute != $urlroute){
        		$navigationRs = Db::name('navigation')->where('lang',$lang)->select();
        		foreach ($navigationRs as $navRs) {
        			if(strpos($navRs['linkurl'],$oldModuleUrlroute.'/') !== false){
        				$linkurl = str_replace($oldModuleUrlroute.'/',$urlroute.'/',$navRs['linkurl']);
        				Db::name('navigation')->where('id',$navRs['id'])->update(['linkurl'=>$linkurl]);
        			}
        		}
        	}
        	/*更新导航表：navigation 结束*/
		}else{//新增
			$moduleRs = new Module;
			$result = $moduleRs->save(input('post.'));

			// 转为小写字母
	        $general = new \common\General();
	        $frommodule = $general->underline_to_ucfirst(input('module'));
	        // tabledir转大写
	        $tabledir = $general->underline_to_ucfirst($tabledir);

			/*新增其他信息 开始*/
			$rootPath = app()->getRootPath(); $appPath = app()->getBasePath(); $modulePath = app()->getAppPath();
			$suffix = config('view.view_suffix'); $separator = DIRECTORY_SEPARATOR;
			//1、复制后台控制器文件
			$fromAdminController = $modulePath.'controller'.$separator.$frommodule.'.php';
			$toAdminController = $modulePath.'controller'.$separator.$tabledir.'.php';
			copy($fromAdminController,$toAdminController);
			//替换模块字符串
			$dofile->editFile($toAdminController,$frommodule,$tabledir);

			//2、复制后台模型文件
			$fromAdminModel = $modulePath.'model'.$separator.$frommodule.'.php';
			$toAdminModel = $modulePath.'model'.$separator.$tabledir.'.php';
			copy($fromAdminModel,$toAdminModel);
			//替换模块字符串
			$dofile->editFile($toAdminModel,$frommodule,$tabledir);

			//3、复制后台验证器文件
			$fromAdminValidate = $modulePath.'validate'.$separator.$frommodule.'.php';
			$toAdminValidate = $modulePath.'validate'.$separator.$tabledir.'.php';
			copy($fromAdminValidate,$toAdminValidate);
			//替换模块字符串
			$dofile->editFile($toAdminValidate,$frommodule,$tabledir);

			//4、复制后台模板文件
			$fromTempPath = $modulePath.'view'.$separator.strtolower($frommodule);
			$toTempPath = $modulePath.'view'.$separator.strtolower($tabledir);
			$dofile->copyFile($fromTempPath,$toTempPath);
			//替换模块字符串
			$dofile->editFile($toTempPath.$separator.'index.'.$suffix,strtolower($frommodule),strtolower($tabledir));//列表页
			$dofile->editFile($toTempPath.$separator.'edit.'.$suffix,strtolower($frommodule),strtolower($tabledir));//编辑页

			//5、复制前台控制器文件
			$fromIndexController = $appPath.$lang.$separator.'controller'.$separator.$frommodule.'.php';
			$toIndexController = $appPath.$lang.$separator.'controller'.$separator.$tabledir.'.php';
			copy($fromIndexController,$toIndexController);
			//替换模块字符串
			$dofile->editFile($toIndexController,$frommodule,$tabledir);

			// 前端默认模板及皮肤
            $theme = Db::name('language')->where('mulu',$lang)->value('template');

			//6、复制前台模板文件
			$fromIndexTempPath = $rootPath.'template'.$separator.$theme.$separator;
			$toIndexTempPath = $rootPath.'template'.$separator.$theme.$separator;
			$dofile->copyFile($fromIndexTempPath.'pc'.$separator.strtolower($frommodule),$toIndexTempPath.'pc'.$separator.strtolower($tabledir));
			//替换模块字符串
			$oldTempModule = 'table="'.strtolower($frommodule).'"'; $newTempModule = 'table="'.strtolower($tabledir).'"';
			$indexPcTempList = $dofile->getFiles($toIndexTempPath.'pc'.$separator.strtolower($tabledir),false,$suffix);
			foreach ($indexPcTempList as $tempRs) {
				$dofile->editFile($toIndexTempPath.'pc'.$separator.strtolower($tabledir).$separator.$tempRs,strtolower($frommodule).$separator,strtolower($tabledir).$separator);//修改链接地址
				$dofile->editFile($toIndexTempPath.'pc'.$separator.strtolower($tabledir).$separator.$tempRs,$oldTempModule,$newTempModule);//修改tag标签的表
			}
			//拷贝移动端模板
			if(is_dir($rootPath.'template'.$separator.$theme.$separator.'mobile')){//如果手机模板存在
			    $dofile->copyFile($fromIndexTempPath.'mobile'.$separator.strtolower($frommodule),$toIndexTempPath.'mobile'.$separator.strtolower($tabledir));
			    //替换模块字符串
			    $indexMobTempList = $dofile->getFiles($toIndexTempPath.'mobile'.$separator.strtolower($tabledir),false,$suffix);
			    foreach ($indexMobTempList as $mobTempRs) {
				    $dofile->editFile($toIndexTempPath.'mobile'.$separator.strtolower($tabledir).$separator.$mobTempRs,strtolower($frommodule).$separator,strtolower($tabledir).$separator);//修改链接地址
				    $dofile->editFile($toIndexTempPath.'mobile'.$separator.strtolower($tabledir).$separator.$mobTempRs,$oldTempModule,$newTempModule);//修改tag标签的表
			    }
			}

			//7、新增数据表
			$oldTable = config('database.connections.mysql.prefix').strtolower($frommodule); $newTable = config('database.connections.mysql.prefix').strtolower($tabledir);
			Db::query("create table if not exists $newTable like $oldTable");
			/*新增其他信息 结束*/
		}
		return $moduleRs->id;
	}

	/**列表
    * @lang 语言变量
    * @order 排序
    */
	static function index($lang = 'cn', $listNum = 20, $order ='sequence desc'){
		if(!empty($lang)){
			$where[] = ['lang','=',$lang];
		}else{
			$where[] = ['id','>',0];
		}
		$pageParam = array('lang'=>input('lang'));

		if(config('app.isdisplay.showmodule') != 1){
			$where[] = ['disabled','=',1];
			$pageParam += array('disabled'=>1);
		}
		
		$rs = Db::name('module')->where($where)->order($order)
			->paginate([
            	'list_rows'=> $listNum,
            	'query'=> $pageParam,
            ]);
		return $rs;
	}

	/**模块
	* table 表
	* sortid 分类ID
    * lang 语言
    * listNum 每页显示数量
    * field 查询字段
    * keyword 关键词
    * order 排序
    * signid 1上架2下架9已删除，大于9就是删除时间戳
    * client app小程序
    * from 来源，navigation导航
    */
	static function infoList($table,$sortid,$lang,$listNum,$field,$keyword,$order,$signid=1,$client='',$from = ''){
		// 转为小写字母
        $general = new \common\General();
        $table = $general->capital_to_underline($table);
        
		$keyword = trim($keyword);
		$where[] = ["$table.lang",'=',$lang];
		switch ($signid) {
			case 9:
				$where[] = ["$table.signid",'>',8];
				break;
			default:
				$where[] = ["$table.signid",'<',10];
				break;
		}
		$auth = new \common\Auth(); $auth->check('','');
		$where[] = ["$table.title|$table.seotitle|$table.keyword|$table.description|$table.content1|sort.title|sort.seotitle|sort.keyword|sort.description",'like',"%$keyword%"];
		$pageParam = array('signid'=>$signid);
		$pageParam += array('tabledir'=>$table);
		$pageParam += array('lang'=>$lang);
		if(!empty($keyword)){
			$pageParam += array('keyword'=>$keyword);
		}
		if(!empty($sortid)){
			$where[] = ["$table.sortid",'=',$sortid];
			$pageParam += array('sortid'=>$sortid);
		}

		//查找模型
		$tableRs = Db::name($table)->where('id','>',0)->find();
		if($tableRs['module'] == 'about' and empty($keyword) and $signid == 1){//单页模型
			$where[] = ["$table.parentid",'=',0];
			$pageParam += array('parentid'=>0);
		}

		// 客户端
		if(!empty($client)){
			$where[] = ["$table.page_sign",'<>',0];
		}
		
		// about模型
      	switch ($table){
            case 'about':
            	$where[] = ["$table.parentid",'=',0];
              	break;
        }

		//查询
		$rs = Db::view($table,$field)
            ->view('sort',['tabledir','title'=>'s_title','seotitle'=>'s_seotitle','keyword'=>'s_keyword','description'=>'s_description'],"sort.id=$table.sortid")
            ->where($where)->order($order)
            ->paginate([
            	'list_rows'=> $listNum,
            	'query'=> $pageParam,
            ]);
        
        $rs = $rs->each(function($item, $key) use ($table){
            // about模型
            switch ($table){
                case 'about':
                    $subArray = Db::name($table)->where('parentid',$item['id'])->select()->toArray();
                    break;
                default:
                  	$subArray = array();
            }
            $item['subArray'] = $subArray;
            return $item;
        });
        
        // 如果是导航
        if($from == 'navigation'){
        	$rs = $rs->each(function($item, $key) use ($table){
				$viewUrl = get_view_url($item['id'],$table,$item['lang']);
                unset($rs['urlroute']);
                $item['urlroute'] = $viewUrl;
                return $item;
            });
        }

		return $rs;
	}
}